<?php

namespace App\Console\Commands;


use App\Http\Clients\ZccmzjgyxmClient;
use App\Models\CmzjAreaModel;
use Illuminate\Console\Command;

class fetchCmzjAreaCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cmzj:area {num_per_each?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取村民之家的area';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $t = time()-86400;
        $areaAvailCodes = ['310000']; $levels = [2,3,4];
        $this->fetchTopCity($areaAvailCodes,$t);


        $this->info("fetchCmzjAreaCommand .");
        while(1) {
            $sencond = date('s');
            $sleepRatio = 1;
            $sleep = 1;

            if ($sencond >= 55) {
                $this->info("sencond = $sencond, wait for next time.");
                break;
            }else  $this->info("sencond = $sencond, keep going.");
            $num = $this->argument('num_per_each') ?? 1;

            foreach ( $areaAvailCodes AS $availCode )
            {

                foreach ( $levels as $level ) {
                        $this->fetchCity($num,$level, $availCode,$t);
                }
            }


            sleep($sleep*$sleepRatio);
        }
        //
        return 0;
    }
    private function fetchTopCity($topCodes,$t)
    {
        $result = CmzjAreaModel::query()->whereIn('code',$topCodes)->where('updated_at', '<', $t)->value('code');
        if( !empty($result) ){
            CmzjAreaModel::query()->whereIn('top_code',$result)->delete();

            $result = (new ZccmzjgyxmClient())->getCityMaps();

            $this->_batchInsertArea($result['data'], 0, 1, $topCodes);
        }

    }


    private function fetchCity($num,$level, $topCode,$t)
    {
        $result = CmzjAreaModel::query()->where(['level'=>$level-1])->where('updated_at','<',$t)->limit($num)->get();
        if( !empty($result ) )
        {
            $data = $result->toArray();
            $ids = [];
            foreach( $data as $row ){
                $result = (new ZccmzjgyxmClient())->getCityMaps($row['code']);
                $this->_batchInsertArea($result['data'],$row['code'],$level, $topCode);
                $ids[] = $row['code'];
            }
            CmzjAreaModel::query()->whereIn('code',$ids)->update(['updated_at'=>time()]);
        }else{
            echo 'done';
        }
    }
    private function _batchInsertArea($data, $parentCode, $level, $topCode)
    {
        if( empty($data) ) return true;
        if( is_array($topCode) ) $topCodes = $topCode;
        else $topCodes = 0;
        foreach( $data as $row ){
            if( !empty($topCodes) ) {
                if( in_array($row['code'], $topCodes) ) $topCode = $row['code'];
                else continue;
            }
            $insertData[] = [
                'parent_code' => $parentCode,
                'code'      => $row['code'],
                'level_name'    => $row['level_name'],
                'name'      => $row['name'],
                'top_code'  => $topCode,
                'level'     => $level
            ];
        }
        CmzjAreaModel::query()->insert($insertData);
    }
}
